package site.marqstree.latte.core.net.rx;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import site.marqstree.latte.core.storage.LattePreference;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.core.net.rx
 * 文件名: AddCookieIntercepter
 * 创建者: marqstree
 * 创建时间: 2020/2/1 10:43
 * 描述: 从sp中取出webview中拦截到的后端web服务器的cookie
 * 将该cookie附加到原生http请求中，使得原生api能跨域访问webview的后端web服务器
 */
public final class AddCookieIntercepter implements Interceptor {

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        final Request.Builder builder = chain.request().newBuilder();
        //从sp中获取WebView访问后端web服务器时拦截到的cookie
        String cookieWebView = LattePreference.getCustomAppProfile("cookie");
        if(cookieWebView!=null&&!cookieWebView.equals("")) {
            Observable.just(cookieWebView)
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(@NonNull String cookie) throws Exception {
                            //给原生API请求附加上WebView拦截下来的cookie
                            builder.addHeader("Cookie", cookie);
                        }
                    });
        }
        return chain.proceed(builder.build());
    }
}
